<template>
  <div class="book-list-container">
    <div class="page-header">
      <h2>图书管理</h2>
      <el-button 
        v-if="userRole === 'admin'" 
        type="primary" 
        @click="handleAddBook">
        添加图书
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
        v-model="queryParams.keyword"
        placeholder="请输入关键词搜索"
        clearable
        class="search-input"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 图书列表表格 -->
    <el-table
      v-loading="loading"
      :data="bookList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="书名" min-width="150" />
      <el-table-column prop="author" label="作者" width="120" />
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="isbn" label="ISBN" width="150" />
      <el-table-column prop="createTime" label="添加时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="viewBookDetail(scope.row.id)"
          >
            查看
          </el-button>
          <el-button
            v-if="userRole === 'admin'"
            type="success"
            size="small"
            @click="editBook(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="userRole === 'admin'"
            type="danger"
            size="small"
            @click="confirmDeleteBook(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getBookList, deleteBook } from '@/api/book'
import { ElMessageBox, ElMessage } from 'element-plus'

// 路由实例
const router = useRouter()
// 用户存储
const userStore = useUserStore()
// 获取用户角色
const userRole = computed(() => userStore.role)

// 加载状态
const loading = ref(false)
// 图书列表数据
const bookList = ref([])
// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
})

// 页面加载时获取图书列表
onMounted(() => {
  getBooks()
})

// 获取图书列表
const getBooks = async () => {
  loading.value = true
  try {
    const res = await getBookList(queryParams)
    if (res.code === 200) {
      bookList.value = res.data.records || res.data.list || res.data
      total.value = res.data.total || res.data.length || 0
    } else {
      ElMessage.error(res.msg || '获取图书列表失败')
    }
  } catch (error) {
    console.error('获取图书列表异常:', error)
    ElMessage.error('获取图书列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1 // 重置到第一页
  getBooks()
}

// 重置搜索
const resetSearch = () => {
  queryParams.keyword = ''
  handleSearch()
}

// 页码改变
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getBooks()
}

// 每页条数改变
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  queryParams.pageNum = 1 // 重置到第一页
  getBooks()
}

// 查看图书详情
const viewBookDetail = (id) => {
  router.push(`/book/detail/${id}`)
}

// 添加图书
const handleAddBook = () => {
  router.push('/book/add')
}

// 编辑图书
const editBook = (id) => {
  router.push(`/book/edit/${id}`)
}

// 确认删除图书
const confirmDeleteBook = (id) => {
  ElMessageBox.confirm('确定要删除这本图书吗？此操作不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDeleteBook(id)
  }).catch(() => {
    // 取消删除，不执行任何操作
  })
}

// 删除图书
const handleDeleteBook = async (id) => {
  try {
    const res = await deleteBook(id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getBooks() // 重新加载图书列表
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除图书异常:', error)
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.book-list-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.search-container {
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  background-color: var(--card-background);
  padding: 16px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
  transition: box-shadow 0.3s;
}

.search-container:hover {
  box-shadow: var(--shadow-medium);
}

.search-input {
  width: 300px;
  margin-right: 12px;
}

:deep(.el-input__wrapper) {
  border-radius: var(--radius-medium);
}

:deep(.el-table) {
  border-radius: var(--radius-medium);
  overflow: hidden;
  box-shadow: var(--shadow-base);
}

:deep(.el-table__header-wrapper) {
  background-color: var(--primary-light);
}

:deep(.el-table__header) {
  background-color: var(--primary-light);
}

:deep(.el-table th) {
  background-color: var(--primary-light);
  font-weight: 600;
  color: var(--text-primary);
  padding: 12px 0;
}

:deep(.el-table tr) {
  transition: all 0.3s;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button) {
  transition: all 0.3s;
  border-radius: var(--radius-small);
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  background-color: var(--card-background);
  padding: 16px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .search-container {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .search-input {
    width: 100%;
    margin-right: 0;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .page-header h2 {
    margin-bottom: 12px;
  }
}
</style> 